package com.world.rickcloudendpoint.net.server;

import com.world.rickcloudendpoint.demo.QueueConstantKey;
import com.world.rickcloudendpoint.demo.redis.RedisQueueSender;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.log4j.Log4j2;

/**
 * @description:  配置 netty server 处理器
 * @author: jlsong
 * @date: 2021/12/07 00:07:17
 * @version: 1.0
 */
@Log4j2
@ChannelHandler.Sharable
public class ReceptionChannelHandler extends ChannelInboundHandlerAdapter {

    final RedisQueueSender queueSender;

    public ReceptionChannelHandler(RedisQueueSender queueSender) {
        this.queueSender = queueSender;
    }

    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Channel active......");
    }

    /**
     * 客户端发消息会触发
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("服务器收到消息: {}", msg.toString());

//        ctx.write("我是服务端，我收到你的消息了！");
//        String queueName = QueueConstantKey.BATCH_DATA_VERIFY;
//        queueSender.sendMsg(queueName, msg.toString());
        ctx.flush();
    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
